<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
	<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
	<!-- Button -->
	<input disabled id="list-sdcard" type="button"
		value="List SDCard Contents" />
	<hr>
		
	<!-- Place Holder for placing the SD Card Listing -->
	<div id="result"></div>
	<hr>

	<script type="text/javascript" src="phonegap-0.9.3.js"></script>
	<script type="text/javascript" src="directorylisting.js"></script>
	
	<script type="text/javascript">
	
		document.addEventListener('deviceready', function() {
			var btn = document.getElementById("list-sdcard");
						
			btn.onclick = function() {
						dirListing("/sdcard");
			}
	
			btn.disabled = false;			
	

		}, true);

		function dirListing(dir){
				window.plugins.directorylisting.list(dir,
						function(r) {
							printResult(r)
						},
						function(e) {
							console.log(e)
						} 
						);
		}
		
		function playMedia(fileName){
				window.plugins.directorylisting.startActivity(fileName,
						function(r) {
							printResultActivity(r)
						},
						function(e) {
							console.log(e)
						} 
						);
		}
		
		function printResult(fileInfo) {
			var innerHtmlText = getHtml(fileInfo);
			document.getElementById("result").innerHTML = innerHtmlText;
		}

		function printResultActivity(status){
			document.getElementById("result").innerHTML = "Media player is loading ...";
		}
		
		function getHtml(fileInfo) {
			
			var htmlText = "<ul><li><div id='div-location'>Location: " + fileInfo.filename + "</div>";			
			var fileName = fileInfo.filename + "";			
			if (fileName != "/sdcard"){
								
				var previousDir = ""; 
				var tempArray = fileName.split("/");
				for (var i = 1; i < tempArray.length - 1; i++){
					previousDir = previousDir + "/" + tempArray[i];
				}
				console.log("previousDir : " + previousDir);
				htmlText = htmlText + "<a href=\"javascript:dirListing('"+ previousDir +"')\">../</a><br/>";
			}
			
			if (fileInfo.children) {
				for ( var index = 0; index < fileInfo.children.length; index++) {
									
					var isdir = fileInfo.children[index].isdir;
					var str = fileInfo.filename + "/" + fileInfo.children[index].filename;					
					if (isdir){					
						
						htmlText = htmlText +  "<a href=\"javascript:onclickFolder('" + str + "')\">" + fileInfo.children[index].filename + "/</a><br/>";	
					}else{
						
						htmlText = htmlText +  "<a href=\"javascript:onclickFile('"+ str +"')\">" + fileInfo.children[index].filename + "</a><br/>";
					}					
				}
			}
			
			htmlText = htmlText + "</li></ul>";
			return htmlText;
		}		
		
		function onclickFile(fileName){
				console.log("fileName: " + fileName);
				playMedia(fileName);
		}
		
		function onclickFolder(folderName){
				console.log("folderName: " + folderName);
				dirListing(folderName);
		}
		
	</script>
</body>

</html>